package ltd.nullpointer.tcp.core;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.apachecommons.CommonsLog;
import ltd.nullpointer.tcp.core.constant.AesKeyHolder;
import ltd.nullpointer.tcp.core.resolver.MessageResolverFactory;
import ltd.nullpointer.tcp.core.util.AesUtil;

import java.util.Arrays;

/**
 * 
 * @ClassName: EncryptMessageEncoder
 * @Description: encrypt data via AES
 * @author zhangweilin
 * @date 2017年11月9日 下午1:25:39
 *
 */
@CommonsLog
public class EncryptMessageEncoder extends MessageToByteEncoder<ByteBuf> {

	@Override
	protected void encode(ChannelHandlerContext ctx, ByteBuf in, ByteBuf out) throws Exception {
		// 是否需要走加密逻辑
		boolean isNeedEncrypt = MessageResolverFactory.getInstance().getResolver(in).isNeedEncrypt();
		//todo 改为reset方式
//		ByteBuf copy = in.retainedDuplicate();
		int len = in.readableBytes();
		byte[] bytes = new byte[len];
		in.readBytes(bytes);
		in.resetReaderIndex();
//		in.skipBytes(in.readableBytes());


		String aesKey = getAesKey(ctx);
		// if (StringUtils.isNotEmpty(aesKey)) {
		log.debug("是否需要加密:"+isNeedEncrypt);
		if (isNeedEncrypt) {
			log.debug("加密前: " + Arrays.toString(bytes));
			bytes = AesUtil.aesEncode(aesKey, bytes);
			log.debug("加密后: " + Arrays.toString(bytes));
		}
		out.writeBytes(bytes);
		bytes = null;
	}

	protected String getAesKey(ChannelHandlerContext ctx) {
		return AesKeyHolder.getAesKey();
	}
}
